package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import jdk.internal.org.objectweb.asm.tree.analysis.Value;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping(value="/v1/users/")
public class UserController {
    @Autowired
    UserMapper userMapper;
@PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
    System.out.println("userRegDTO = " + userRegDTO);
   UserVO userVO= userMapper.selectByusername(userRegDTO.getUsername());
   if(userVO!=null){
       return 2;
   }
   User user=new User();
    BeanUtils.copyProperties(userRegDTO,user);
    user.setCreated(new Date());
   userMapper.insert(user);
   return 1;

}
@PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
    System.out.println("userLoginDTO = " + userLoginDTO);
   UserVO userVO=userMapper.selectByusername(userLoginDTO.getUsername());
   if(userVO==null){
       return 3;
   }
   if(userVO.getPassword().equals(userLoginDTO.getPassword())){
       session.setAttribute("user",userVO);
       return 1;
   }
   return 2;
}
@GetMapping("currentUser")
public UserVO currentUser(HttpSession session){
    UserVO userVO =(UserVO) session.getAttribute("user");

    return userVO;
}
@GetMapping("logout")
    public void logout(HttpSession session){
    session.removeAttribute("user");
}

}
